<?php
/**
 * User: rongxia
 * Date: 2018/08/07
 * Time: 23:42
 */

namespace App\Services\ThirdAPI;


use common\utils\RedisKeys;
//use App\Models\Order;
use App\Models\Game;
use App\Models\Partner;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use common\utils\SysCode;

class CQ9APIService
{
    protected $apiName = 'CQ9';

    /**
     * 代理商获取玩家游戏下注数据或总社获取玩家游戏下注日志   OK
     * @param int $startTime 抓取时间段的开始时间
     * @param int $endTime 抓取时间段的结束时间
     * @return string|unknown
     */
    public function getCQ9Orders($startTime, $endTime)
    {
        Log::info("CQ9 获取注单：" . date("Y-m-d H:i:s", $startTime) . " - " . date("Y-m-d H:i:s", $endTime));
        $retValue = [];
        $bet = $this->getBetLog($startTime, $endTime);
        if (is_array($bet) && count($bet)) {
            $retValue = array_merge($retValue, $bet);
        } else {
            Log::info("CQ9 暂无可更新数据");
        }
        return $retValue;
    }

    /**
     * 获取cq9游戏名字列表
     * @return array|bool
     */
    public function getCQ9GameNames()
    {
        $data = Game::where(['partner_name' => $this->apiName])->get()->toArray();
        $needUpdate = Redis::set(RedisKeys::CQ9_LOCK_GAMES, date("Y-m-d H:i:s"), 'nx', 'ex', 3600);
        if (!$data || $needUpdate) {
            $data = $this->getCQ9GameList($data);
        }
//        $data = $this->getCQ9GameList($data);
        $games = [];
        foreach ($data as $game) {
            $games[$game['game_code']] = $game['name'];
        }
        return $games;
    }

    /**
     * 获取游戏列表
     */
    public function getCQ9GameList($currentData)
    {
        $url = config('app.rpcserver') . "/api/getGameList";
        Log::info("CQ9 游戏列表请求接口 url: " . $url);
        $res = GameApiService::request($url, "get", ['api_name' => $this->apiName]);
        $formatData = [];
        foreach ($currentData as $value) {
            $formatData[$value['game_code']] = $value;
        }
        $partnerInfo = GameApiService::getApiPartnerInfoByName($this->apiName);
        $insertData = [];
        foreach ($res as $value) {
            if (empty($formatData[$value['gamecode']])) {
                $insertData[] = array(
                    'partner_id' => $partnerInfo['id'],
                    'partner_name' => $this->apiName,
                    'name' => $value['nameset'][array_flip($value['lang'])['zh-cn']]['name'],
                    'game_code' => $value['gamecode'],
                    'game_type' => 1,
                    'type' => $value['gametype'],
                    'img_url' => "/game/cq9/" . $value['gamecode'] . ".png",
                    'status' => $value['status'] ? 1 : 0,
                );
            }
        }
        if (count($insertData) > 0) {
            $res = GameApiService::saveGame($insertData);
            if (!$res) {
                Redis::del(RedisKeys::CQ9_LOCK_GAMES);
                $msg = "CQ9 CQ9APIService::getCQ9GameList 保存游戏列表报错失败：" . json_encode($res->getErrors(), JSON_UNESCAPED_UNICODE);
                Log::error($msg);
                return error_exit(SysCode::INTERNAL_SERVER_ERROR, $msg);
            }
        }
        $currentData = array_merge($currentData, $insertData);
        return $currentData;
    }

    /**
     * 获取用户投注记录
     * @param string $starttime 开始时间(时间戳)
     * @param string $endtime 开始时间(时间戳)
     * @return
     */
    public function getBetLog($starttime, $endtime, $page = 1, $pagesize = 1000)
    {
        $params = [
            'api_name' => $this->apiName,
            'start_time' => $starttime,
            'end_time' => $endtime,
//            'start_time' => 1539597600,//测试用数据
//            'end_time' => 1539684000,//测试用数据
        ];
        $url = config('app.rpcserver') . "/api/getOrders";
        Log::info("CQ9 请求接口 url: {$url}, data: " . json_encode($params));
        $response = GameApiService::request($url, 'get', $params);
        $msg = "CQ9 获取注单抓取接口请求url:====" . $url . "请求参数:======" . json_encode($params, JSON_UNESCAPED_UNICODE) . "请求时间:====" . date("Y-m-d H:i:s") . "总共有" . count($response) . "条数据";
        Log::info($msg);
        amount_format_array($response, ['bet_money','prize_money','winloss_money','contribute_money','bonus_money','valid_money'], true);
        return $response;
    }

}